package dataBase;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;

import com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException;

public class SqlTable implements ISqlTable {
	protected Statement stmt = null;
	String tableName = "";
	Map<String, String> schema = null;
	String engine = "";
	final static String INNO = "INNODB";
	final static String ISAM = "MYISAM";

	public SqlTable(Statement stmt, String tableName,
			Map<String, String> schema, String engine) {
		if ((stmt == null)
				|| (tableName.equals(""))
				|| (schema == null)
				|| ((!engine.toUpperCase().equals(INNO)) && (!engine
						.toUpperCase().equals(ISAM)))) {
			throw new IllegalArgumentException();
		}
		this.stmt = stmt;
		this.tableName = tableName;
		this.schema = schema;
		this.engine = engine;
	}

	@Override
	public Map<String, String> getSchema() {
		return schema;
	}

	@Override
	public boolean createTable() throws SQLException {
		String createQuery = "CREATE TABLE " + tableName;
		createQuery += "(" + createColumns(schema) + ") engine = " + engine
				+ ";";
		boolean res;
		try{
			res =  stmt.execute(createQuery);
		}
		catch (MySQLSyntaxErrorException e){
			// TODO: check how to catch the exception
			// table already exist
			return true;
		}
		return res;
	}

	@Override
	public boolean createTable(List<String> primaryKey) throws SQLException {
		String createQuery = "CREATE TABLE " + tableName;
		createQuery += "(" + createColumns(schema) + ", primary key(";
		for (String key : primaryKey) {
			createQuery += key + ",";
		}
		createQuery = createQuery.substring(0,createQuery.length() - 1);
		createQuery += ")) engine = " + engine + ";";//TODO: update function
		boolean res;
		try {
			res = stmt.execute(createQuery);
		}
		catch (MySQLSyntaxErrorException e){
			// TODO: check how to catch the exception
			// table already exist
			return true;
		}
		return res;
	}

	@Override
	public boolean insertRecord(List<String> values) throws SQLException {
		String insertQuery = "insert into " + tableName + " values(";
		insertQuery += values.toString().substring(1, values.toString().length() - 1) + ");";
		return stmt.execute(insertQuery);
	}

	String createColumns(Map<String, String> schemas) {
		String res = "";
		for (String column : schemas.keySet()) {
			res += column + " " + schemas.get(column) + ",";
		}
		res = res.substring(0, res.length() - 1);
		return res;
	}
	

}
